﻿using System;
using System.ComponentModel.Composition;
using System.Data;
using System.Data.Entity;
using WeBlog.Interfaces;
using WeBlog.Models;

namespace WeBlog.DataContext
{
    [Export(typeof(IUnitOfWork))]
    public class WeBlogContext : DbContext, IUnitOfWork
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<Page> Pages { get; set; }        
        public DbSet<PostComment> PostComments { get; set; }
        public DbSet<PostRating> PostRatings { get; set; }
        public DbSet<PostVisit> PostVisits { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Widget> WidgetSettings { get; set; }         

        public void Save()
        {
            SaveChanges();
        }

        public void Commit()
        {
            base.SaveChanges();
        }

        public void Attach<T>(T entity) where T : class, IModel
        {
            Set<T>().Attach(entity);
            Entry(entity).State = EntityState.Modified;
        }

        public void Add<T>(T entity) where T : class, IModel
        {
            Set<T>().Add(entity);
        }

        public bool Remove<T>(T item) where T : class, IModel
        {
            try
            {
                Set<T>().Remove(item);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public T Find<T>(params object[] keyValues) where T : class, IModel
        {
            return Set<T>().Find(keyValues);
        }

        public IDbSet<T> DbSet<T>() where T : class, IModel
        {
            return Set<T>();
        }
    }
}
